package monopoli.gui;

import java.io.FileNotFoundException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import monopoli.Monopoli;
import monopoli.MonopoliView;
import monopoli.communication.Communication;
import monopoli.communication.RMIAddress;
import org.jdesktop.application.Action;



/**
 *
 * @author Marco
 */
public class JSettingHost extends javax.swing.JDialog {

    private final static long serialVersionUID = 1232131233134L;
    private MonopoliView frameView;

    /** Creates new form JInitializationServer */
    public JSettingHost(java.awt.Frame parent, boolean modal, MonopoliView fv) {
        super(parent, modal);
        frameView = fv;
        initComponents();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblMonopoliJ = new javax.swing.JLabel();
        lblInizioPartita = new javax.swing.JLabel();
        cmdImpostaClient = new javax.swing.JButton();
        lblIpServer = new javax.swing.JLabel();
        lblIp = new javax.swing.JLabel();
        jListaInterfacce = new javax.swing.JComboBox();
        jListaIp = new javax.swing.JComboBox();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setModal(true);
        setName("Form"); // NOI18N
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }
        });

        lblMonopoliJ.setFont(new java.awt.Font("Segoe Print", 1, 36));
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(monopoli.MonopoliApp.class).getContext().getResourceMap(JSettingHost.class);
        lblMonopoliJ.setText(resourceMap.getString("lblMonopoliJ.text")); // NOI18N
        lblMonopoliJ.setName("lblMonopoliJ"); // NOI18N

        lblInizioPartita.setFont(resourceMap.getFont("lblInizioPartita.font")); // NOI18N
        lblInizioPartita.setText(resourceMap.getString("lblInizioPartita.text")); // NOI18N
        lblInizioPartita.setFocusCycleRoot(true);
        lblInizioPartita.setName("lblInizioPartita"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(monopoli.MonopoliApp.class).getContext().getActionMap(JSettingHost.class, this);
        cmdImpostaClient.setAction(actionMap.get("setClientSettings")); // NOI18N
        cmdImpostaClient.setFont(resourceMap.getFont("cmdImpostaClient.font")); // NOI18N
        cmdImpostaClient.setText(resourceMap.getString("cmdImpostaClient.text")); // NOI18N
        cmdImpostaClient.setName("cmdImpostaClient"); // NOI18N
        cmdImpostaClient.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                cmdImpostaClientMouseClicked(evt);
            }
        });

        lblIpServer.setFont(resourceMap.getFont("lblIpServer.font")); // NOI18N
        lblIpServer.setText(resourceMap.getString("lblIpServer.text")); // NOI18N
        lblIpServer.setName("lblIpServer"); // NOI18N

        lblIp.setFont(resourceMap.getFont("lblIp.font")); // NOI18N
        lblIp.setText(resourceMap.getString("lblIp.text")); // NOI18N
        lblIp.setName("lblIp"); // NOI18N

        jListaInterfacce.setName("jListaInterfacce"); // NOI18N

        jListaIp.setName("jListaIp"); // NOI18N

        jButton1.setAction(actionMap.get("updateListaIp")); // NOI18N
        jButton1.setText(resourceMap.getString("jButton1.text")); // NOI18N
        jButton1.setName("jButton1"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(133, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(lblInizioPartita)
                    .addComponent(lblMonopoliJ)
                    .addComponent(cmdImpostaClient, javax.swing.GroupLayout.PREFERRED_SIZE, 132, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(163, 163, 163))
            .addGroup(layout.createSequentialGroup()
                .addGap(34, 34, 34)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblIpServer)
                    .addComponent(lblIp))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jListaInterfacce, 0, 235, Short.MAX_VALUE)
                    .addComponent(jListaIp, 0, 235, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addGap(26, 26, 26))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblMonopoliJ, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(lblInizioPartita)
                .addGap(20, 20, 20)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblIpServer, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jListaInterfacce, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblIp, javax.swing.GroupLayout.DEFAULT_SIZE, 23, Short.MAX_VALUE)
                    .addComponent(jListaIp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addGap(29, 29, 29)
                .addComponent(cmdImpostaClient, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated

        try {

            jListaInterfacce.removeAllItems();
            jListaIp.removeAllItems();
            boolean first = true;

            //Elenca tutte le interfacce del sistema col ip utilizzato
            Enumeration<NetworkInterface> e1 = NetworkInterface.getNetworkInterfaces();
            while (e1.hasMoreElements()) {

                NetworkInterface ni = e1.nextElement();
                jListaInterfacce.addItem(ni.getName());

                if (first) {
                    Enumeration<InetAddress> e2 = ni.getInetAddresses();
                    while (e2.hasMoreElements()) {

                        InetAddress ia = e2.nextElement();
                        jListaIp.addItem(ia.toString().substring(1));
                    }
                    first = false;
                }
            }
        }
        catch (SocketException ex) {
            Logger.getLogger(JSettingHost.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_formWindowActivated

    private void cmdImpostaClientMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cmdImpostaClientMouseClicked

        String bindName = "";
        //String ip = jListaIp.getSelectedItem().toString();
        String ip = "130.136.4.137";
        int port = 2000;

        /*   Lettura da file INI
        HashMap parameters=null;
        String iniFileName = "Parameters.ini";
        IniParser iniFile=null;
        try {
            iniFile = new IniParser("Parameters.ini");
        }
        catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        parameters = new HashMap();
        ip = iniFile.getValue("HOST","ip");
        port = Integer.parseInt(iniFile.getValue("HOST", "port"));
        */
         

        //Imposta a livello comunicazione l'oggetto myHostAddress
        Communication com = Monopoli.getMonopoliCommunication();
        boolean ret = com.setHost(ip, port);
        RMIAddress myRMIA = com.getHost();

        bindName = myRMIA.getBindName();
        ip = myRMIA.getIp();
        port = myRMIA.getPort();

        if (ret) {
            //Aggiorna la DebugConsole
            Monopoli.getMonopoliGUI().getGestoreRefresh()
                    .refreshDebugConsole( "[DBG_gui] Impostazione host con bindName=" + bindName +
                    " Ip=" + ip +
                    " porta=" + port);

            //Aggiorna la tab del Dati Client
            Monopoli.getMonopoliGUI().getGestoreRefresh()
                    .refreshHostData(bindName, ip, Integer.toString(port), "", "", "");

        }
        else
            //Aggiorna la DebugConsole
            Monopoli.getMonopoliGUI().getGestoreRefresh()
                    .refreshDebugConsole( "[DBG_gui] Impostazione del host locale fallita");
        

        this.dispose();
        
    }//GEN-LAST:event_cmdImpostaClientMouseClicked

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                JSettingHost dialog = new JSettingHost(new javax.swing.JFrame(), true, null);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    @Action
    public void updateListaIp() {

        int cont = 0;
        int sel = jListaInterfacce.getSelectedIndex();

        if (sel<0) return;

        try {
            jListaIp.removeAllItems();

            //Scorre le interfacce di rete fino a quella selezionata nella combo
            Enumeration<NetworkInterface> e1 = NetworkInterface.getNetworkInterfaces();
            NetworkInterface ni = e1.nextElement();
            while (e1.hasMoreElements() && cont!=sel) {
                ni = e1.nextElement();
                cont++;
            }

            //Estrae tutti gli indirizzi: IPv4 e IPv6 dell'interfaccia
            Enumeration<InetAddress> e2 = ni.getInetAddresses();
            while (e2.hasMoreElements()) {
                InetAddress ia = e2.nextElement();
                jListaIp.addItem(ia.toString().substring(1));
            }

            //jListaInterfacce.setSelectedIndex(sel);
        }
        catch (SocketException ex) {
            Logger.getLogger(JSettingHost.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cmdImpostaClient;
    private javax.swing.JButton jButton1;
    private javax.swing.JComboBox jListaInterfacce;
    private javax.swing.JComboBox jListaIp;
    private javax.swing.JLabel lblInizioPartita;
    private javax.swing.JLabel lblIp;
    private javax.swing.JLabel lblIpServer;
    private javax.swing.JLabel lblMonopoliJ;
    // End of variables declaration//GEN-END:variables
}
